package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.constant.Oauth2Constant;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberOAuthVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * （2）通过第三方授权访问首页
 * 处理社交登陆
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    //http://auth.gulimall.com/oauth2.0/gitee/success?code=b43c71db8f207af30474f8331d76789c7cf705899ef7b276b7e60bb35c83cabd
    @GetMapping("/oauth2.0/gitee/success")
    public String oauth2(@RequestParam("code") String code, HttpSession httpSession) throws Exception {

        HttpResponse post = null;
        try {
            //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
            Map<String,String> map = new HashMap<>();
            map.put("grant_type",Oauth2Constant.OAUTH2_GRANT_TYPE);
            map.put("code",code);
            map.put("client_id", Oauth2Constant.OAUTH2_CLIENT_ID);
            map.put("redirect_uri",Oauth2Constant.OAUTH2_RIDIRECT_URI);
            map.put("client_secret",Oauth2Constant.OAUTH2_CLIENT_SECRET);
            //String host, String path, String method,
            //Map<String, String> headers,
            //Map<String, String> querys,
            //Map<String, String> bodys
            post = HttpUtils.doPost("https://gitee.com", "/oauth/token", "POST", new HashMap<>(), map, new HashMap<>());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //取出token
        //获取状态行的响应码，如果是200就代表响应成功
        if (post.getStatusLine().getStatusCode() == 200){
            HttpEntity entity = post.getEntity();
            //将HttpEntity转换成String类型
            String entityJsonString = EntityUtils.toString(entity);
            //Json字符串 -> java对象  参数必须是String类型Json串
            SocialUser socialUser = JSON.parseObject(entityJsonString,SocialUser.class);

            //判断账号是否是第一次登陆，如果是第一次登陆就直接注册到会员服务
            R<MemberOAuthVo> r = memberFeignService.oauth2Login(socialUser);
            if (r.getCode() == 0){
                MemberOAuthVo memberOAuthVo = r.getData(new TypeReference<MemberOAuthVo>() {});
                log.info("用户信息:{}",memberOAuthVo);
                httpSession.setAttribute("loginUser",memberOAuthVo);
                return "redirect:http://gulimall.com";
            }
        }else {
            //获取失败 -> 重定向到登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }

        //第三方授权成功 -> 跳转至登陆页
        return "redirect:http://gulimall.com";

    }

}
